package de.goals.paulzerr;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	public static String message = "";
	private static final String URL_GOALS = "http://www.goals.paulzerr.de/android_php/loginandroid.php";
	private Button button;
	private EditText emailEditText;
	private EditText passwordEditText;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		emailEditText = (EditText) findViewById(R.id.editText1);
		passwordEditText = (EditText) findViewById(R.id.editText2);
		((TextView)findViewById(R.id.textLoginFailed)).setText("");
		button = (Button) findViewById(R.id.button1);
		loadPreferences();
		
		if (!isOnline()){ 
			TextView failedText = (TextView) findViewById(R.id.textLoginFailed);
			failedText.setText("Please check internet connection!");
			return;
		} 
		
		emailEditText = (EditText) findViewById(R.id.editText1);
		passwordEditText = (EditText) findViewById(R.id.editText2);
		button = (Button) findViewById(R.id.button1);
		loadPreferences();

		button.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				if (!isOnline()) {
					TextView failedText = (TextView) findViewById(R.id.textLoginFailed);
					failedText.setText("Please check internet connection!");
					return;
				}
				
				Editable email = emailEditText.getText();
				Editable password = passwordEditText.getText();
				Map<String, String> params = new HashMap<String, String>();
				params.put("email", email.toString());
				params.put("password", password.toString());

				@SuppressWarnings("unchecked")
				Map<String, String>[] parameters = new Map[4];
				params.put("url",URL_GOALS );
				parameters[0] = params;
				AsyncTask<Map<String, String>, Void, JSONObject> task = new GoalsPageConnector().execute(parameters);
				
				JSONObject response = null;
				try {
					response = task.get();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (ExecutionException e1) {
					e1.printStackTrace();
				}
				String responseMessage = "";
				String userid = "";
				try {
					responseMessage = response.get("login").toString();
					userid = response.get("userid").toString();
				} catch (JSONException e) {
					e.printStackTrace();
				}

				if (responseMessage.equals("failed")) {
					TextView failedText = (TextView) findViewById(R.id.textLoginFailed);
					failedText.setText("Login failed.Please try again.");
				} else if (responseMessage.equals("successful")) {
					Bundle bundle = new Bundle();
					bundle.putString("userid", userid);

					Intent newIntent = new Intent(MainActivity.this,
							OverviewActivity.class);
					newIntent.putExtras(bundle);

					savePreferences("emailpreset", emailEditText.getText()
							.toString());
					savePreferences("passwordpreset", passwordEditText
							.getText().toString());

					startActivity(newIntent);
				} else if (responseMessage.equals("Invalid login data")) {
					TextView failedText = (TextView) findViewById(R.id.textLoginFailed);
					failedText.setText(responseMessage);
				}
			}
		});
	}

	private void savePreferences(String key, String value) {
		SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(key, value);
		editor.commit();
	}

	private void loadPreferences() {
		SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
		String strSavedMailPreset = sharedPreferences.getString("emailpreset",
				"");
		String strSavedPasswordPreset = sharedPreferences.getString(
				"passwordpreset", "");

		if (!(strSavedMailPreset.equals("") || strSavedPasswordPreset
				.equals(""))) {
			emailEditText.setText(strSavedMailPreset);
			passwordEditText.setText(strSavedPasswordPreset);
		}

	}

	
	public boolean isOnline() {
	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo ni = cm.getActiveNetworkInfo();
	    if (ni!=null && ni.isAvailable() && ni.isConnected()) {
	        return true;
	    } else {
	        return false; 
	    }
	}
}
